package jadeCW.behaviour;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jadeCW.HospitalAgent;
import jadeCW.output.Printer;

public class UpdateAppointments extends CyclicBehaviour {
	/**
	 * Type identifier for message
	 */
	public static final String TYPE = "update-appointment";

	/**
	 * Generated serialisation ID
	 */
	private static final long serialVersionUID = -6145166922043187727L;

	public void action() {
		// must be run on a hospital
		if (!(myAgent instanceof HospitalAgent)) {
			return;
		}

		HospitalAgent hospital = (HospitalAgent) myAgent;

		// prepare the template to receive messages
		MessageTemplate template = MessageTemplate.and(MessageTemplate
				.MatchPerformative(ACLMessage.INFORM), MessageTemplate
				.MatchConversationId(TYPE));

		// possibly receive a message
		ACLMessage message = hospital.receive(template);

		// if no message received, block and try again
		if (message == null) {
			block();
			return;
		}

		// get the sender and owner of the requested swap
		AID requester = message.getSender();
		int requestedAppointment = Integer.valueOf(message.getContent());
		AID requestOwner = hospital.getOwner(requestedAppointment);
		
		Printer.printUpdateReceive(hospital, requester, requestOwner, requestedAppointment);

		// check the patient is not swapping with themselves or no-one
		if (requestOwner == null || requestOwner.equals(requester)) {
			return;
		}

		int offeredAppointment = hospital.getAppointment(requester);

		// if someone else has requested the other half of the swap
		if (hospital.isSwapRequest(requestOwner, offeredAppointment)) {
			hospital.removeSwapRequest(requestOwner, offeredAppointment);

			hospital.setAppointment(offeredAppointment, requestOwner);
			hospital.setAppointment(requestedAppointment, requester);
		} else {
			// add request to swap and wait for other agent to confirm swap
			hospital.addSwapRequest(requester, requestedAppointment);
		}
	}
}
